import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_admin_privileges/cave_admin_privileges_model.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_manage_member/cave_member_model.dart';
import 'package:cave_flutter/utils/whl_dialog_util.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class CaveManageMemberLogic extends GetxController {
  int caveId = 0;
  int caveRole = 0;
  CaveAdminPrivilegesModel? adminPrivilegesModel;

  // 搜索相关
  String keyword = '';

  // 分页相关
  int current = 1;
  int pageSize = 20;
  bool hasMore = false;

  bool isLoading = false;

  TextEditingController editingController = TextEditingController();
  List<CaveMemberModel> memberList = [];

  EasyRefreshController refreshController = EasyRefreshController(controlFinishRefresh: true, controlFinishLoad: true);

  @override
  void onInit() {
    super.onInit();

    var arguments = Get.arguments;
    if (arguments != null) {
      caveId = arguments['caveId'];
      caveRole = arguments['caveRole'];
      adminPrivilegesModel = arguments['adminPrivilegesModel'];
    }

    pullRefreshData();
  }

  onSearch(String text) async {
    keyword = text;
    pullRefreshData();
  }

  void onClear() {
    keyword = '';
    pullRefreshData();
  }

  /// 下拉刷新
  void pullRefreshData() {
    requestData(1);
  }

  /// 上拉加载更多
  void loadMoreData() {
    if (!hasMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    requestData(current + 1);
  }

  /// 加载指定页的数据
  void requestData(int page) {
    if (isLoading) return;
    isLoading = true;
    var params = {'caveId': caveId, 'current': page, 'size': pageSize, 'nickName': keyword};
    WhlApi.pageCaveUser.get(params).then((value) {
      if (value.isSuccess()) {
        Map data = value.data;

        if (page == 1) {
          memberList.clear();
        }

        if (data["records"] != null) {
          for (var element in data["records"]) {
            memberList.add(CaveMemberModel.fromJson(element));
          }
        }

        current = data['current'] ?? 1;
        int pages = current = data['pages'] ?? 1;
        hasMore = pages > current;
      } else {
        MyToast.show(value.msg ?? "获取成员列表失败");
      }

      refreshController.finishRefresh();
      if (page == 1) {
        refreshController.resetFooter();
      } else {
        if (hasMore) {
          refreshController.finishLoad();
        } else {
          refreshController.finishLoad(IndicatorResult.noMore);
        }
      }

      isLoading = false;
      update();
    });
  }

  void setAdmin(CaveMemberModel memberModel) async {
    ResponseData responseData =
        await WhlApi.caveHandleAdmin.get({"id": memberModel.id, "handle": memberModel.isAdmin == 1 ? 0 : 1}, withLoading: true);
    if (responseData.isSuccess()) {
      memberModel.isAdmin = memberModel.isAdmin == 1 ? 0 : 1;
    } else {
      MyToast.show(responseData.msg ?? "设置失败");
    }
  }

  void setGuest(CaveMemberModel memberModel) async {
    ResponseData responseData =
        await WhlApi.caveHandleGuest.get({"id": memberModel.id, "handle": memberModel.isGuest == 1 ? 0 : 1}, withLoading: true);
    if (responseData.isSuccess()) {
      memberModel.isGuest = memberModel.isGuest == 1 ? 0 : 1;
    } else {
      MyToast.show(responseData.msg ?? "设置失败");
    }
  }

  void setProhibit(CaveMemberModel memberModel) async {
    ResponseData responseData =
        await WhlApi.caveHandleProhibit.get({"id": memberModel.id, "handle": memberModel.prohibit == 1 ? 0 : 1}, withLoading: true);
    if (responseData.isSuccess()) {
      memberModel.prohibit = memberModel.prohibit == 1 ? 0 : 1;
    } else {
      MyToast.show(responseData.msg ?? "设置失败");
    }
  }

  void removeMember(CaveMemberModel memberModel) {
    WhlDialogUtil.showConfirmDialog("", description: '确认移除该成员吗？', sureString: '确定', cancelString: '我再想想', sureAction: () {
      WhlApi.caveRemoveMember.get({"id": memberModel.id}, withLoading: true).then((value) {
        if (value.isSuccess()) {
          memberList.remove(memberModel);
          update();
        } else {
          MyToast.show(value.msg ?? "移除失败");
        }
      });
    });
  }
}
